package handler

import (
	"fmt"
	"ginadmin/models"
	"ginadmin/routes/context"
	"ginadmin/utils"
	"github.com/gin-gonic/gin"
)

type OrganizationHandler struct {
}

func (org *OrganizationHandler) Router(group *gin.RouterGroup) {
	group.GET("/org/list", org.List)
	group.POST("/org/add", org.Add)
	group.POST("/org/update", org.Update)
	group.POST("/org/del", org.Del)
}

func (org *OrganizationHandler) List(c *gin.Context) {
	orgList := models.List()
	context.Map(c, context.M{"code": 200, "msg": "OK", "data": orgList})
}

func (org *OrganizationHandler) Del(c *gin.Context) {
	req := c.Request
	orgId := req.FormValue("orgId")

	if orgId == "" {
		context.Err(c, 400, "机构Id不能为空")
		return
	}

	//TODO 查找role name 如果有重复的。直接返回报错
	organization := &models.Organization{}
	result := organization.FindOrgById(orgId)
	if !result {
		context.Err(c, 400, "此机构不存在")
		return
	}

	//查找是否有下级机构。有下级机构的不能删除
	subOrgResult := models.FindOrgByParentId(orgId)
	fmt.Println("subOrgResult", subOrgResult)
	if subOrgResult {
		context.Err(c, 400, "此机构存在下级机构，不能删除")
		return
	}
	//TODO 要查找是否有用户。有用户的不能删除

	/*err := organization.DelOrg()
	if err != nil {
		context.Err(c, 400, err.Error())
		return
	}*/
	context.OK(c)
}

func (org *OrganizationHandler) Update(c *gin.Context) {
	req := c.Request
	name := req.FormValue("name")
	orgId := req.FormValue("orgId")

	if orgId == "" {
		context.Err(c, 400, "机构Id不能为空")
		return
	}

	if name == "" {
		context.Err(c, 400, "机构名称不能为空")
		return
	}

	//TODO 查找role name 如果有重复的。直接返回报错
	organization := &models.Organization{}
	result := organization.FindOrgById(orgId)
	if !result {
		context.Err(c, 400, "此机构不存在")
		return
	}
	fmt.Println(organization)
	err := organization.Update(name)
	if err != nil {
		context.Err(c, 400, err.Error())
		return
	}
	context.OK(c)
}

func (org *OrganizationHandler) Add(c *gin.Context) {
	req := c.Request
	parentId := req.FormValue("parentId")
	name := req.FormValue("name")
	parentName := req.FormValue("parentName")

	if parentId == "" {
		context.Err(c, 400, "上级机构Id不能为空")
		return
	}
	if parentName == "" {
		context.Err(c, 400, "上级机构名称不能为空")
		return
	}
	if name == "" {
		context.Err(c, 400, "机构名称不能为空")
		return
	}

	//根据parentId 查找上级机构--判断上级机构是否存在
	//TODO 查找role name 如果有重复的。直接返回报错
	parentorg := &models.Organization{}
	result := parentorg.FindOrgById(parentId)
	if !result {
		context.Err(c, 400, "此机构不存在")
		return
	}

	fmt.Println("parentOrg==>", parentorg)

	o := models.Organization{Name: name, ParentId: utils.StrToUInt(parentId), ParentName: parentName,
		Ancestors: parentorg.Ancestors + "," + utils.UintToStr(parentorg.ID)}
	o.Add()
	context.OK(c)
}
